package br.edu.utfpr.md.tads.controller;

import java.util.ArrayList;

import br.edu.utfpr.md.tads.R;
import br.edu.utfpr.md.tads.controller.adapter.ContatoListAdapter;
import br.edu.utfpr.md.tads.controller.connections.ContatosConnection;
import br.edu.utfpr.md.tads.model.Contato;
import android.app.Activity;
import android.app.Dialog;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

public class DialogConnection extends AsyncTask<String, Void, Boolean> {
	private Dialog dialog;
	private ListView listViewContatos;
	private Activity activity;
	
	public DialogConnection(Activity activity, ListView listViewContatos) {
		this.activity = activity;
		this.listViewContatos = listViewContatos;
		dialog = new Dialog(activity);
	}
	protected void onPreExecute() {
		dialog.setContentView(R.layout.dialog_progress);
		dialog.setCancelable(false);
		dialog.show();
	};
	
	@Override
	protected Boolean doInBackground(String... params) {
		try {
			ContatosConnection connection = new ContatosConnection(activity);
			final ArrayList<Contato> contatos;
			if(params.length == 0){
				contatos = connection.getAll();
				
			}else{
				contatos = connection.getBuscar(params[0]);
			}
			activity.runOnUiThread(new Runnable() {
				public void run() {
					ContatoListAdapter contatoListAdapter = new  ContatoListAdapter(activity, contatos);
					listViewContatos.setAdapter(contatoListAdapter);
			}});
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return false;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		dialog.dismiss();
		if (!result) {
			Toast.makeText(activity, "Servidor Indiponivel", Toast.LENGTH_LONG);
		}
	}

}
